package com.tm;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

/**
 * 系统配置文件装载
 * @author XIAOXI
 */
public class PropertySupport {

	private static final String CONFIG_FILE = "application.properties";

	protected static Log logger = LogFactory.getLog(PropertySupport.class);

	protected static Properties p = new Properties();

	static {
		init(CONFIG_FILE);
	}

	protected static void init(String propertyFileName) {
		InputStream in = null;
		try {
			in = PropertySupport.class.getClassLoader().getResourceAsStream(propertyFileName);
			if (in != null) {
				p.load(in);
				
				if (logger.isInfoEnabled()) {
					logger.info("系统配置文件装载成功~");
					
					//cookie配置装在入配置文件
					/*SysService ss  = SpringContextLoader.getBean(SysService.class);
					
					Map cfg = ss.getCookieCfg(p.getProperty("application.id", "CENTER"));
					
					p.setProperty("cookie.name", cfg.get("global_name").toString());
					p.setProperty("cookie.domain", cfg.get("global_value").toString());*/
				}
			}
		} catch (IOException e) {
			logger.error("装载 [" + propertyFileName + "] 异常:" + e.getMessage(), e);
			System.out.println("load system config file was fucked!");
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
					in = null;
					logger.error("释放 [" + propertyFileName + "] 异常:" + e.getMessage(), e);
					System.out.println("system config file was fucked!");
				}
		}
	}

	public static String getProperty(String key, String defaultValue) {
		if(StringUtils.isEmpty(p.getProperty(key)))
			return defaultValue;
		else
			return p.getProperty(key);
	}

	public static String getProperty(String key) {
		return p.getProperty(key);
	}

	public static void reload() {
		reload(CONFIG_FILE);
	}

	public static void reload(String filename) {
		if (p != null) {
			p.clear();
		}
		init(filename);
	}
}
